package com.gnerv.pabu.basic.core.exception;

import com.gnerv.pabu.basic.core.entity.Result;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.session.UnknownSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @description: 全局异常处理
 * @author: Gnerv LiGen
 * @date: 2018-08-01
 **/
@ControllerAdvice
public class GlobalExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 权限异常处理
     */
    @ExceptionHandler(value = AuthorizationException.class)
    @ResponseBody
    public Result authorizationExceptionHandler(HttpServletRequest req, Exception e) {
        logger.info(e.getMessage(), e);
        return Result.response(Result.CODE_405);
    }

    /**
     * 会话异常处理
     */
    @ExceptionHandler(value = UnknownSessionException.class)
    @ResponseBody
    public Result unknownSessionExceptionHandler(HttpServletRequest req, Exception e) {
        logger.info(e.getMessage(), e);
        return Result.response(Result.CODE_401);
    }

    /**
     * 业务异常处理
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public Result businessExceptionHandler(HttpServletRequest req, Exception e) {
        logger.info(e.getMessage(), e);
        return Result.response(Result.CODE_400, e.getMessage());
    }

    /**
     * 通用异常处理
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result defaultErrorHandler(HttpServletRequest req, Exception e) {
        logger.info(e.getMessage(), e);
        return Result.response(Result.CODE_500);
    }

}

